<?php
declare(strict_types=1);

namespace App\Admin\Controller;

use App\Common\Controller\AbstractController;
use App\Common\Logic\CommonLogic;
use App\Server\Model\AdminMenu;
use App\Admin\Validate\MenuValidate;
use App\Common\Validate\Validate;
use App\Server\Model\Admin;
use App\Server\Model\AdminGroup;
use Hyperf\Di\Annotation\Inject;
use App\Admin\Validate\IndexValidate;
use Hyperf\Utils\Context;

class MenuController extends AbstractController
{

    /**
     * @Inject()
     * @var MenuValidate
     */
    protected $MenuValidate;

    public function index()
    {
        $page = $this->request->query('page');
        if ($page) {
            $AdminMenu = new AdminMenu();
            $list = $AdminMenu->getCacheList([], 'menu_all');
            foreach ($list as $k => $v) {
                // 默认全部展开
                // $list[$k]['spread'] = true;
                // 标注菜单和纯权限节点
                $v['is_menu'] == 1?$list[$k]['title'] = '<span class="layui-badge">权限</span> <span class="layui-badge layui-bg-blue">菜单</span> ' . $v['title']:$list[$k]['title'] = '<span class="layui-badge">权限</span> ' . $v['title'];
            }
            $list = list_to_tree($list);
            return $this->success($list);
        }
        return $this->render->render('/admin/menu/index');
    }

    public function add()
    {
        $session = $this->session->all();
        $model = new AdminMenu();
        $page = $this->request->query('page');
        if ($page){
            //是提交操作
            $param = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $errorMessage = $this->MenuValidate->add($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }

            $param['is_menu'] = empty($param['is_menu'])?0:$param['is_menu'];
            $addRes = $model->dataAdd($param);
            if(false == $addRes) {
                return $this->error('添加失败');
            } else {
                $model->clearCacheData();
                addlog($this->request,$session['admin']['id'],'添加菜单信息成功');
                return $this->success(['url'=>'/admin/menu/index'],'添加菜单信息成功');
            }
        } else {
            $menus = $model->getCacheList([],'menu_all');
            $menus = (new CommonLogic())->taglist($menus);
            $data = [];
            $data['menu'] = $menus;
            return $this->render->render('admin/menu/add',$data);
        }
    }



    public function edit()
    {
        $session = $this->session->all();
        //获取菜单id
        $getRes = $this->request->all();
        $id = !empty($getRes['id']) ? $getRes['id'] : 0;
        $model = new AdminMenu();
        $page = $this->request->query('page');
        if ($page){
            //是提交操作
            $param = $this->request->post();
            //验证  唯一规则： 表名，字段名，排除主键值，主键名
            $errorMessage = $this->MenuValidate->edit($this->request);
            //验证部分数据合法性
            if ($errorMessage) {
                return $this->error('提交失败：' . $errorMessage);
            }

            $where = [];
            $where[] = ['id','=',$id];
            //验证菜单是否存在
            $menu = $model->getInfo($where,['id']);
            if(empty($menu)) {
                return $this->error('id不正确');
            }
            $param['is_menu'] = empty($param['is_menu'])?0:$param['is_menu'];
            $addRes = $model->dataUpdate($where,$param);
            if(false == $addRes) {
                return $this->error('修改失败');
            } else {
                $model->clearCacheData();
                addlog($this->request,$session['admin']['id'],'修改菜单信息成功');
                return $this->success(['url'=>'/admin/menu/index'],'修改菜单信息成功');
            }
        } else {
            //非提交操作
            $where = [];
            $where[] = ['id','=',$id];
            //验证菜单是否存在
            $menuData = $model->getInfo($where,'*');

            $menus = $model->getCacheList([],'menu_all');
            $menus = (new CommonLogic())->taglist($menus);
            $data = [];
            $data['menu'] = $menus;
            if(!empty($menuData)) {
                $data['data'] = $menuData;
                return $this->render->render('admin/menu/edit',$data);
            } else {
                return $this->error('id不正确');
            }
        }

    }


    public function delete()
    {
        $adminInfo = Context::get('adminInfo');
        $page = $this->request->query('page');
        if ($page) {
            $id = $this->request->query('id');
            $adminMenu = new AdminMenu();
            $childMenu = $adminMenu->getList([['pid','=',$id]],['*']);
            if(empty($childMenu)) {
                $adminMenu -> dataDelete([['id','=',$id]]);
                if(false == $adminMenu) {
                    return $this->error('删除失败');
                } else {
                    $adminMenu->clearCacheData();
                    addlog($this->request, $adminInfo['id'], '删除菜单');//写入日志
                    return $this->success([],'删除成功');
                }
            } else {
                return $this->error('该菜单下还有子菜单，不能删除');
            }
        }
    }


    public function orders()
    {
        if($this->request->isPost()) {
            $post = $this->request->post();
            $i = 0;
            foreach ($post['id'] as $k => $val) {
                $order = Db::name('admin_menu')->where('id',$val)->value('orders');
                if($order != $post['orders'][$k]) {
                    if(false == Db::name('admin_menu')->where('id',$val)->update(['orders'=>$post['orders'][$k]])) {
                        return $this->error('更新失败');
                    } else {
                        $i++;
                    }
                }
            }
            addlog();//写入日志
            return $this->success('成功更新'.$i.'个数据','admin/menu/index');
        }
    }

}
